using UnityEngine;
using UnityEditor;
using UnityEditor.EditorTools;
using System;
using System.IO;

namespace TCC.Framework.Tools
{
    [EditorTool("创建图标", typeof(GameObject))]
    public class CreateIcon : EditorTool
    {
        GUIContent _gUI;
        GameObject _target;
        string iconName;
        IconType iconType = IconType.jpg;
        string savePath;
        Vector2Int iconSize = new Vector2Int(512, 512);
        Color bgColor;

        Editor _editor;
        private Material mat;

        private Material Mat
        {
            get
            {
                if (mat == null)
                {
                    mat = new Material(Shader.Find("IconAlpha"));
                    mat.hideFlags = HideFlags.HideAndDontSave;
                }
                return mat;
            }
        }

        public override GUIContent toolbarIcon
        {
            get
            {
                if (_gUI == null)
                {
                    _gUI = new GUIContent();
                    _gUI.image = EditorGUIUtility.IconContent("d_RawImage Icon").image;
                    _gUI.tooltip = "创建图标";
                }
                return _gUI;
            }
        }

        public void OnEnable()
        {
            EditorTools.activeToolChanged += ToolChanged;
            Selection.selectionChanged += ToolChanged;
        }

        public void OnDisable()
        {
            EditorTools.activeToolChanged -= ToolChanged;
            Selection.selectionChanged -= ToolChanged;
            _editor = null;
        }

        public void OnDestroy()
        {
            _editor = null;
        }

        public void ToolChanged()
        {
            if (!EditorTools.IsActiveTool(this)) return;
            _target = target as GameObject;
            iconName = _target == null ? "" : _target.name + "." + iconType.ToString();
            if (string.IsNullOrEmpty(savePath))
                savePath = Application.dataPath;
            bgColor = bgColor == null ? Color.black : bgColor;
            _editor = Editor.CreateEditor(_target, typeof(PreviewInspector));
        }

        public override void OnToolGUI(EditorWindow window)
        {
            if (_target == null) return;
            Handles.BeginGUI();
            Rect rect = Rect.zero;
            float _w = 300;
            float _h = 350;
            float _x = window.position.width / 2 - _w / 2;
            float _y = window.position.height / 2 - _h / 2;

            rect.Set(_x, _y, _w, _h);
            int id = GUIUtility.GetControlID(FocusType.Passive, rect);
            HandleUtility.AddDefaultControl(id);
            GUI.Box(rect, "", "window");
            rect.Set(_x + 3, _y + 3, 55, 20);
            GUI.Label(rect, "保存名称：");
            rect.Set(_x + 58, _y + 3, _w - 62, 20);
            iconName = GUI.TextField(rect, iconName);
            rect.Set(_x + 3, _y + 24, 55, 20);
            GUI.Label(rect, "保存路径：");
            rect.Set(_x + 58, _y + 24, _w - 92, 20);
            savePath = GUI.TextField(rect, savePath);
            rect.Set(_x + (_w - 92) + 60, _y + 24, 30, 20);
            if (GUI.Button(rect, EditorGUIUtility.IconContent("d_Folder Icon")))
            {
                savePath = EditorUtility.OpenFolderPanel("保存", "Assets/", "Assets/");
            }
            rect.Set(_x + 3, _y + 45, 55, 20);
            GUI.Label(rect, "文件大小：");
            rect.Set(_x + 58, _y + 45, _w - 62, 20);
            iconSize = EditorGUI.Vector2IntField(rect, "", iconSize);
            rect.Set(_x + 3, _y + 66, 55, 20);
            GUI.Label(rect, "保存类型：");
            rect.Set(_x + 58, _y + 66, 70, 20);
            iconType = (IconType)EditorGUI.EnumPopup(rect, iconType);
            if (iconType == IconType.jpg)
            {
                rect.Set(_x + 128, _y + 66, 55, 20);
                GUI.Label(rect, "背景颜色：");
                rect.Set(_x + 183, _y + 66, _w - 186, 20);
                bgColor = EditorGUI.ColorField(rect, bgColor);
            }
            rect.Set(_x + 3, _y + 87, 55, 20);
            GUI.Label(rect, "预览：");
            rect.Set(_x + 3, _y + 108, _w - 6, 200);
            _editor.DrawPreview(rect);
            rect.Set(_x + 3, _y + _h - 23, _w - 6, 20);
            if (GUI.Button(rect, "保存"))
            {
                SaveIcon();
            }
            GUI.enabled = true;
            Handles.EndGUI();
        }

        private void SaveIcon()
        {
            if (_editor == null) return;
            Texture2D icon = (_editor as PreviewInspector).PreviewTexture;
            if (icon != null)
                SaveTextureAsFile(icon, iconName);
        }

        public void SaveTextureAsFile(Texture2D texture, string folderName)
        {
            byte[] bytes;
            string extension;
            switch (iconType)
            {
                case IconType.png:
                    texture = GetTexture(texture, false);
                    bytes = texture.EncodeToPNG();
                    extension = ".png";
                    break;
                case IconType.jpg:
                    texture = GetTexture(texture, true);
                    bytes = texture.EncodeToJPG();
                    extension = ".jpg";
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            string path = $"{savePath}/{folderName}{extension}";
            File.WriteAllBytes(path, bytes);
            AssetDatabase.Refresh();
        }

        private Texture2D GetTexture(Texture2D iconTex, bool isAddBg)
        {
            if (iconTex != null)
            {
                Mat.SetTexture("_IconTex", iconTex);//给Shader的属性赋值
                if (isAddBg)
                {
                    Mat.SetColor("_Color", bgColor);
                    Mat.SetFloat("_IsPng", 0);
                }
                else
                    Mat.SetFloat("_IsPng", 1);
            }

            RenderTexture tempRT = new RenderTexture(iconSize.x, iconSize.y, 32, RenderTextureFormat.ARGB32);//生成纹理
            tempRT.Create();
            Texture2D temp2 = new Texture2D(tempRT.width, tempRT.height, TextureFormat.ARGB32, false);
            Graphics.Blit(temp2, tempRT, Mat);//将temp2纹理的值通过mat赋值到tempRT
            RenderTexture prev = RenderTexture.active;
            RenderTexture.active = tempRT;//设置当前active的纹理

            Texture2D output = new Texture2D(tempRT.width, tempRT.height, TextureFormat.ARGB32, false);//创建一个RGBA格式的纹理
            output.ReadPixels(new Rect(0, 0, tempRT.width, tempRT.height), 0, 0);//读取当前active的纹理            
            output.Apply();//apply将改变写入
            RenderTexture.active = prev;

            return output;
        }

        public enum IconType
        {
            png,
            jpg
        }
    }
}

